package cn.kasa.org.controller;

import cn.kasa.basic.utils.AjaxResult;
import cn.kasa.basic.utils.PageList;
import cn.kasa.org.domain.Department;
import cn.kasa.org.query.DepartmentQuery;
import cn.kasa.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
@Api(value = "部门的API" , description="部门相关的CRUD功能")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    @ApiOperation(value = "查询全部" )
    public List<Department> loadAll(){
        return departmentService.loadAll();
    }

    @GetMapping("/{id}")

    public Department loadById(@PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            departmentService.remove(id);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后再试！");
        }
    }


    @PutMapping
    public AjaxResult addOrUpt(@RequestBody Department department){
        try{
            if(department.getId() == null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请重试！");
        }
    }

    @PostMapping
    public PageList<Department> queryData(@RequestBody DepartmentQuery departmentQuery){
        System.out.println(departmentQuery);
        PageList<Department> departments = departmentService.queryData(departmentQuery);
        return departments;
    }

    @PatchMapping
    public AjaxResult batchDepartment(@RequestBody  Long[] ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        }catch (Exception e){
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请重试！");
        }
    }

    @GetMapping("/tree")
    public List<Department> tree(){
        return departmentService.tree();
    }
}
